import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'TextNumberLimitFormatter.dart';

/// 输入框和表单
///
class FieldFormWidget extends StatefulWidget {
  FieldFormWidget({
    Key? key,
    @required this.text,
  }) : super(key: key);
  final String? text;

  @override
  State<StatefulWidget> createState() {
    return _CheckSwitchState(text ?? "");
  }
}

class _CheckSwitchState extends State<FieldFormWidget> {
  String? text;
  bool ?isInputPhone;
  bool ?isInputCode;
  String ? mobile = "";
  String ?code = "";
  Timer ?timer;
  int ?total = 0;
  bool ?canSendCode;

  _CheckSwitchState(String? str) {
    this.text = str;
  }

  @override
  void initState() {
    super.initState();
    isInputPhone = false;
    isInputCode = false;
    canSendCode = false;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        backgroundColor: Colors.grey[300], //背景色
        appBar: AppBar(
          title: Text(text??""),
        ),
        body: GestureDetector(
          onTap: () {
            Focus.of(context).requestFocus(FocusNode());
          },
          child: Container(
              padding: EdgeInsets.only(left: 28.0, top: 28.0, right: 28.0),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    TextField(
                      keyboardType: TextInputType.number,

                      inputFormatters: [TextNumberLimitFormatter(11, 0)],
                      //整数11位
                      decoration: new InputDecoration(
                          helperText: '用户名长度为6-10个字母',
                          helperStyle: TextStyle(color: Colors.blue),
                          helperMaxLines: 1

                          // errorText: '用户名输入错误',
                          // errorStyle: TextStyle(fontSize: 12),
                          // errorMaxLines: 1,
                          // errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),

                          // labelText: '手机号', //labelText显示在输入框上边
                          // labelStyle: TextStyle(color: Colors.red),
                          // hintText: '请输入手机号',
                          // border: InputBorder.none,
                          ),
                      onChanged: inputPhoneChanged,
                    ),
                    // Divider(
                    //   color: Colors.black,
                    // ),
                    SizedBox(
                      height: 30,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                          child: TextField(
                            decoration: new InputDecoration(
                              hintText: '请输入验证码',
                              // border: InputBorder.none,
                            ),
                            onChanged: inputCodeChanged,
                          ),
                        ),
                        Container(
                          width: 120.0,
                          child: TextButton(
                            // elevation: 5.0,
                            // //正常状态下的阴影
                            // highlightElevation: 8.0,
                            // ////按下时的阴影
                            // color: Colors.blue,
                            // //按钮背景颜色
                            // highlightColor: Colors.blue[700],
                            // //按钮按下时的背景颜色
                            // colorBrightness: Brightness.dark,
                            // splashColor: Colors.grey,
                            //点击时，水波动画中水波的颜色
                            child: Text("发送验证码"),
                            // shape: RoundedRectangleBorder(
                            //     //圆角等
                            //     borderRadius: BorderRadius.circular(20.0)),
                            onPressed: () {
                              sendCodeButtonClick();
                            }, //按钮点击回调
                          ),
                        ),
                      ],
                    ),

                    Container(
                        margin: EdgeInsets.only(top: 40),
                        child: MaterialButton(
                          onPressed: loginButtonClick(),
                          color: Color.fromRGBO(40, 110, 240, 1.0),
                          textColor: Color.fromRGBO(255, 255, 255, 1),
                          highlightColor: Color.fromRGBO(255, 255, 255, 1),
                          disabledColor: Color.fromRGBO(215, 215, 215, 1.0),
                          child: Text('登录'),
                          minWidth: double.infinity,
                          height: 44,
                          elevation: 4,
                        )),
                    SizedBox(
                      height: 20,
                    ),
                    TextField(
                      keyboardType: TextInputType.number,

                      inputFormatters: [TextNumberLimitFormatter(11, 0)],
                      //整数11位
                      decoration: new InputDecoration(
                        prefixIcon: Icon(Icons.person),
                        errorText: '用户名输入错误',
                        errorStyle: TextStyle(fontSize: 12),
                        errorMaxLines: 1,
                        errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.red)),
                      ),
                      onChanged: inputPhoneChanged,
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextField(
                      keyboardType: TextInputType.number,

                      inputFormatters: [TextNumberLimitFormatter(11, 0)],
                      //整数11位
                      decoration: new InputDecoration(
                        suffixIcon: Icon(Icons.person),
                        labelStyle: TextStyle(color: Colors.red),
                        hintText: '请输入手机号',
                      ),
                      onChanged: inputPhoneChanged,
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Container(
                      height: 60,
                      child: TextField(
                        decoration: InputDecoration(
                          fillColor: Color(0xffefefef),
                          filled: true,
                          enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.orange),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(100))),
                          hintText: 'QQ号/手机号/邮箱',
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.red),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(100))),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                  ],
                ),
              )),
        ));
  }

  void inputPhoneChanged(String phone) {
    setState(() {
      if (phone.isNotEmpty) {
        isInputPhone = true;
        canSendCode = true;
      } else {
        isInputPhone = false;
        canSendCode = false;
      }
    });
    mobile = phone;
  }

  void inputCodeChanged(String string) {
    setState(() {
      if (string != null && string.length > 0) {
        isInputCode = true;
      } else {
        isInputCode = false;
      }
    });
    code = string;
  }

  loginButtonClick() {
    if (isInputPhone! && isInputCode!) {
      return () {
        Fluttertoast.showToast(msg: '发起请求', gravity: ToastGravity.CENTER);
      };
    } else {
      return null;
    }
  }

  sendCodeButtonClick() {
    if (canSendCode!) {
      sendCode();
    } else {
      Fluttertoast.showToast(msg: '请输入电话号码', gravity: ToastGravity.CENTER);
    }
  }

  void sendCode() {
    if (!isChinaPhoneLegal(mobile??"")) {
      Fluttertoast.showToast(msg: '请输入正确的电话号码', gravity: ToastGravity.CENTER);
    } else {
      Fluttertoast.showToast(msg: '发送成功！', gravity: ToastGravity.CENTER);
    }
  }

  ///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
  /// 此方法中前三位格式有：
  /// 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
  bool isChinaPhoneLegal(String str) {
    return new RegExp(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }
}
